import Vue, { VNodeData } from 'vue';
import permissionPersist from '@/persists/permissionPersist';


function hasPermission(featureName: string, ability: string): boolean {
    const permissions = permissionPersist.get();
    return permissions.filter((p) => p.feature_name === featureName && p.ability === ability).length > 0;
}

/**
 * v-can directive
 * Usage:
 * v-can:<ability_name> = "'<feature_name>'"
 * Example:
 * v-can:update-sub-information="'event'"
 */
Vue.directive('can', (el, binding, vnode) => {
    const featureName = binding.value;
    const ability = binding.arg as string;

    if (!hasPermission(featureName, ability)) {
        // replace HTMLElement with comment node
        const comment = document.createComment(' ');
        Object.defineProperty(comment, 'setAttribute', {
            value: () => undefined,
        });
        vnode.elm = comment;
        vnode.text = ' ';
        vnode.isComment = true;
        vnode.context = undefined;
        vnode.tag = undefined;
        // @ts-ignore
        (vnode.data as VNodeData).directives = undefined;

        if (vnode.componentInstance) {
            // @ts-ignore
            vnode.componentInstance.$el = comment;
        }

        if (el.parentNode) {
            el.parentNode.replaceChild(comment, el);
        }
    }
});
